package com.threegroup.admin.service.impl;

import com.threegroup.admin.dao.SysDeptDao;
import com.threegroup.admin.dao.SysUserDao;
import com.threegroup.admin.dto.SysDeptDTO;
import com.threegroup.admin.entity.SysDeptEntity;
import com.threegroup.admin.enums.SuperAdminEnum;
import com.threegroup.admin.security.user.SecurityUser;
import com.threegroup.admin.service.ISysDeptService;
import com.threegroup.common.constant.Constant;
import com.threegroup.common.exception.ErrorCode;
import com.threegroup.common.exception.TakeOutException;
import com.threegroup.common.utils.BeanCopierUtils;
import com.threegroup.common.utils.RequestHolder;
import com.threegroup.common.utils.TreeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class SysDeptServiceImpl implements ISysDeptService {

    @Resource
    private SysDeptDao sysDeptDao;

    @Resource
    private SysUserDao sysUserDao;

    /**
     * 获取部门列表
     * @param params
     * @return
     */
    @Override
    public List<SysDeptDTO> list(Map<String, Object> params) {
        //普通管理员，只能查询所属部门及子部门的数据
        SecurityUser user = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user.getSuperAdmin() == SuperAdminEnum.NO.value()) {
            params.put("deptIdList", getSubDeptIdList(user.getDeptId()));
        }

        //查询部门列表
        List<SysDeptEntity> entityList = sysDeptDao.getList(params);

        List<SysDeptDTO> dtoList = BeanCopierUtils.copyList(entityList, SysDeptDTO.class);

        return TreeUtils.build(dtoList);
    }

    /**
     * 获取子部门列表
     * @param deptId
     * @return
     */
    @Override
    public List<Long> getSubDeptIdList(Long deptId) {
        List<Long> deptIdList = sysDeptDao.getSubDeptIdList(deptId);
        deptIdList.add(deptId);

        return deptIdList;
    }

    /**
     * 新增部门
     * @param sysDeptDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysDeptDTO sysDeptDTO) {

        // 获取当前登录用户Id
        HttpServletRequest request = RequestHolder.getRequest();
        Long userId = Long.valueOf((String) request.getAttribute(Constant.USER_ID));

        SysDeptEntity entity = BeanCopierUtils.copy(sysDeptDTO, SysDeptEntity.class);

        entity.setPids(getPidList(entity.getPid()));
        entity.setCreator(userId);
        entity.setCreateDate(new Date());
        entity.setUpdater(userId);
        entity.setUpdateDate(new Date());

        // 添加部门
        sysDeptDao.save(entity);
    }

    /**
     *
     * @param id 部门id
     * @return
     */
    @Override
    public SysDeptDTO get(Long id) {

        //超级管理员，部门ID为null
        if(id == null){
            return null;
        }

        SysDeptEntity entity = sysDeptDao.getById(id);

        return BeanCopierUtils.copy(entity, SysDeptDTO.class);
    }

    /**
     * 更新部门信息
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysDeptDTO dto) {
        // 获取当前登录用户Id
        HttpServletRequest request = RequestHolder.getRequest();
        Long userId = Long.valueOf((String) request.getAttribute(Constant.USER_ID));
        SysDeptEntity entity = BeanCopierUtils.copy(dto, SysDeptEntity.class);

        //上级部门不能为自身
        if(entity.getId().equals(entity.getPid())){
            throw new TakeOutException(ErrorCode.SUPERIOR_DEPT_ERROR);
        }

        //上级部门不能为下级部门
        List<Long> subDeptList = getSubDeptIdList(entity.getId());
        if(subDeptList.contains(entity.getPid())){
            throw new TakeOutException(ErrorCode.SUPERIOR_DEPT_ERROR);
        }

        entity.setPids(getPidList(entity.getPid()));
        entity.setUpdater(userId);
        entity.setUpdateDate(new Date());

        sysDeptDao.updateById(entity);
    }

    /**
     * 删除部门信息
     * @param id 部门id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        //判断是否有子部门
        List<Long> subList = getSubDeptIdList(id);
        if(subList.size() > 1){
            throw new TakeOutException(ErrorCode.DEPT_SUB_DELETE_ERROR);
        }

        //判断部门下面是否有用户
        int count = sysUserDao.getCountByDeptId(id);
        if(count > 0){
            throw new TakeOutException(ErrorCode.DEPT_USER_DELETE_ERROR);
        }

        //删除
        sysDeptDao.deleteById(id);
    }

    /**
     * 获取所有上级部门ID
     * @param pid 上级ID
     */
    private String getPidList(Long pid){
        //顶级部门，无上级部门
        if(Constant.DEPT_ROOT.equals(pid)){
            return Constant.DEPT_ROOT + "";
        }

        //所有部门的id、pid列表
        List<SysDeptEntity> deptList = sysDeptDao.getIdAndPidList();

        //list转map
        Map<Long, SysDeptEntity> map = new HashMap<>(deptList.size());
        for(SysDeptEntity entity : deptList){
            map.put(entity.getId(), entity);
        }

        //递归查询所有上级部门ID列表
        List<Long> pidList = new ArrayList<>();
        getPidTree(pid, map, pidList);

        return StringUtils.join(pidList, ",");
    }

    /**
     * 递归获取上级部门
     * @param pid 上级部门pid
     * @param map 所有部门id, pid
     * @param pidList 上级部门 pid 列表
     */
    private void getPidTree(Long pid, Map<Long, SysDeptEntity> map, List<Long> pidList) {
        //顶级部门，无上级部门
        if(Constant.DEPT_ROOT.equals(pid)){
            return ;
        }

        //上级部门存在
        SysDeptEntity parent = map.get(pid);
        if(parent != null){
            getPidTree(parent.getPid(), map, pidList);
        }

        pidList.add(pid);
    }
}
